// $Id: util.c 2 2011-04-01 11:19:47Z cedric.shih@gmail.com $
/*
 * Copyright (C) 2010 Cedric Shih <cedric.shih@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>

#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/un.h>
#endif

#include "log.h"

#include "util.h"

int niohttp_test_bind(unsigned short port)
{
	struct sockaddr_in addr;
	int sock = -1;

	if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		goto error;
	}

	addr.sin_family = AF_INET; // host byte order
	addr.sin_port = htons(port); // short, network byte order
	inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr.s_addr);
	memset(addr.sin_zero, '\0', sizeof addr.sin_zero);

	if(bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
		goto error;
	}

	if(listen(sock, 128) < 0) {
		goto error;
	}

	return sock;

error:
	if (sock > 0) {
		close(sock);
	}
	return -1;
}
